package com.jianzong.lingxuan.im;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @auth Leiwenlong
 * @since 2021/1/30
 */
@Slf4j
public class WebSocketNettyServer {

    public static void main(String[] args) {
           //创建两个线程
           NioEventLoopGroup mainGrp = new NioEventLoopGroup(); //主线程池
           NioEventLoopGroup subGrp = new NioEventLoopGroup(); //从线程池

          try {
              //创建Netty服务器启动对象
              ServerBootstrap bootstrap = new ServerBootstrap();

              //创建服务器启动对象
              bootstrap
                      //指定上述定义的主从线程
                      .group(mainGrp, subGrp)
                      //指定Netty通道类型
                      .channel(NioServerSocketChannel.class)
                      //指定通道初始化器用来加载当Channel收到消息事件后 如何进行业务处理
                      .childHandler(new WebsocketChannelInitializer());
              //绑定服务器端口
              ChannelFuture future = bootstrap.bind(9066);
              log.info("启动了sokect服务"+bootstrap);
              //等待服务器关闭
              future.channel().closeFuture().sync();
          }catch (Exception e){
               e.printStackTrace();
              log.error("启动sokect服务失败:"+e.getMessage());
          }finally {
              //关闭服务器
              mainGrp.shutdownGracefully();
              subGrp.shutdownGracefully();
              log.error("sokect服务已销毁");
          }

    }
}
